"""
跑腿代办序列化器
用于跑腿员、订单等数据的序列化与反序列化
"""

from rest_framework import serializers
from .models import ErrandRunner, ErrandOrder
from users.serializers import UserBriefSerializer


class ErrandRunnerListSerializer(serializers.ModelSerializer):
    """跑腿员列表序列化器"""
    user_info = UserBriefSerializer(source='user', read_only=True)
    service_rate = serializers.SerializerMethodField()

    class Meta:
        model = ErrandRunner
        fields = [
            'id', 'user', 'user_info', 'status', 'is_verified',
            'service_areas', 'service_types', 'completed_orders',
            'rating', 'service_rate'
        ]
        read_only_fields = ['id', 'user', 'completed_orders', 'rating']

    def get_service_rate(self, obj):
        """计算服务完成率"""
        if obj.total_orders == 0:
            return 0
        return round((obj.completed_orders / obj.total_orders) * 100, 2)


class ErrandRunnerDetailSerializer(serializers.ModelSerializer):
    """跑腿员详情序列化器"""
    user_info = UserBriefSerializer(source='user', read_only=True)
    service_rate = serializers.SerializerMethodField()
    recent_orders = serializers.SerializerMethodField()

    class Meta:
        model = ErrandRunner
        fields = [
            'id', 'user', 'user_info', 'status', 'is_verified',
            'service_areas', 'service_types', 'total_orders',
            'completed_orders', 'cancelled_orders', 'total_earnings',
            'rating', 'service_rate', 'recent_orders', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'user', 'total_orders', 'completed_orders',
                           'cancelled_orders', 'total_earnings', 'rating', 'created_at', 'updated_at']

    def get_service_rate(self, obj):
        """计算服务完成率"""
        if obj.total_orders == 0:
            return 0
        return round((obj.completed_orders / obj.total_orders) * 100, 2)

    def get_recent_orders(self, obj):
        """获取最近5个已完成订单"""
        orders = obj.orders.filter(status='completed').order_by('-updated_at')[:5]
        return ErrandOrderListSerializer(orders, many=True).data


class ErrandOrderListSerializer(serializers.ModelSerializer):
    """跑腿订单列表序列化器"""
    customer_info = UserBriefSerializer(source='customer', read_only=True)
    runner_info = serializers.SerializerMethodField()
    order_type_display = serializers.CharField(source='get_order_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = ErrandOrder
        fields = [
            'id', 'order_number', 'customer', 'customer_info', 'runner', 'runner_info',
            'order_type', 'order_type_display', 'status', 'status_display',
            'title', 'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'order_number', 'customer', 'runner', 'created_at', 'updated_at']

    def get_runner_info(self, obj):
        """获取跑腿员信息"""
        if obj.runner:
            return {
                'id': obj.runner.id,
                'username': obj.runner.user.username,
                'nickname': obj.runner.user.nickname,
                'avatar': obj.runner.user.avatar.url if obj.runner.user.avatar else None,
                'rating': obj.runner.rating
            }
        return None


class ErrandOrderDetailSerializer(serializers.ModelSerializer):
    """跑腿订单详情序列化器"""
    customer_info = UserBriefSerializer(source='customer', read_only=True)
    runner_info = serializers.SerializerMethodField()
    order_type_display = serializers.CharField(source='get_order_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = ErrandOrder
        fields = [
            'id', 'order_number', 'customer', 'customer_info', 'runner', 'runner_info',
            'order_type', 'order_type_display', 'status', 'status_display',
            'title', 'description', 'pickup_address', 'delivery_address',
            'customer_phone', 'base_fee', 'tip_fee', 'total_fee',
            'expected_pickup_time', 'expected_delivery_time',
            'created_at', 'updated_at'
        ]
        read_only_fields = ['id', 'order_number', 'runner', 'created_at', 'updated_at', 'total_fee']

    def get_runner_info(self, obj):
        """获取跑腿员信息"""
        if obj.runner:
            return UserBriefSerializer(obj.runner.user).data
        return None

    def validate(self, data):
        """验证数据"""
        if 'base_fee' in data and 'tip_fee' in data:
            data['total_fee'] = data['base_fee'] + data['tip_fee']
        return data


# 为了保持兼容性，保留原有的序列化器名称
ErrandRunnerSerializer = ErrandRunnerDetailSerializer
ErrandOrderSerializer = ErrandOrderDetailSerializer